package com.mano233.server.config.exception;

import com.mano233.server.po.ResponseMessage;
import com.mano233.server.po.ResponseStatus;
import com.mano233.server.service.serviceImpl.FastDfsServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class GlobalDefultExceptionHandler {
    private static Logger logger = LoggerFactory.getLogger(FastDfsServiceImpl.class);

    //声明要捕获的异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseMessage defaultExceptionHandler(HttpServletRequest request, Exception e) {
        if (e instanceof UsernameNotFoundException) {
            logger.warn("找不到用户" + e.getMessage());
            return new ResponseMessage(ResponseStatus.INFO, "找不到用户");
        }
        if (e instanceof PasswordEx) {
            logger.warn("密码错误-" + "用户id：" + e.getMessage());
            return new ResponseMessage(ResponseStatus.INFO, "密码错误");
        }
        if (e instanceof MethodArgumentTypeMismatchException) {
            return new ResponseMessage(ResponseStatus.ERROR, "请求参数异常");
        }
        if (e instanceof HttpRequestMethodNotSupportedException) {
            logger.warn("不支持的请求方法" + request.getMethod() + ":" + request.getRequestURI());
            return new ResponseMessage(ResponseStatus.ERROR, "不支持的请求方法" + request.getMethod() + ":" + request.getRequestURI());
        }
        return new ResponseMessage(ResponseStatus.ERROR, "未知异常");
    }
}
